import axios from "axios";
import type { AxiosResponse } from "axios";
import type { ApiResponse } from "@/types";
import { ElMessage } from "element-plus";

const service = axios.create({
    baseURL: process.env.VUE_APP_API_URL,
    timeout: 5000,
    headers: {
        'Content-Type': 'application/json'
    },
    withCredentials: false // 改为 false，因为目前不需要携带凭证
});

// 处理响应数据
const handleResponse = <T>(response: AxiosResponse): ApiResponse<T> => {
    return response.data;
};

// API 请求函数
const apiRequest = async <T>(
    url: string,
    params: any,
    method = "get",
    config: Record<string, any> = {}
): Promise<ApiResponse<T>> => {
    try {
        let response: AxiosResponse;
        const requestConfig = { ...config };

        switch (method.toLowerCase()) {
            case "get":
                response = await service.get(url, { params, ...requestConfig });
                break;
            case "post":
                response = await service.post(url, params, requestConfig);
                break;
            case "put":
                response = await service.put(url, params, requestConfig);
                break;
            case "delete":
                response = await service.delete(url, requestConfig);
                break;
            default:
                throw new Error(`Unsupported method: ${method}`);
        }

        return handleResponse<T>(response);
    } catch (error) {
        if (axios.isAxiosError(error) && error.response?.data) {
            // 返回后端的错误信息
            return error.response.data as ApiResponse<T>;
        }
        // 如果不是后端返回的错误，则返回一个通用错误
        return {
            code: -1,
            data: null as T,
            message: error instanceof Error ? error.message : "请求失败",
        };
    }
};

export default apiRequest;
